<template>
  <div class="com-container">
      <div class="com-chart" ref='stock_ref'></div>
  </div>
</template>

<script>
import {mapState} from 'vuex'
export default {
    data(){
        return{
            //echarts实例对象
            chartInstance:null,
            //保存服务器返回的数据
            allData:null,
            currentIndex:0, //当前所展示页数（总共10个，5个1页）
            titleFontSize:0, //标题文字大小
            timerId:null    //定时器标识
        }
    },
    created() {
        //在组件创建的时候进行webSocket回调函数的注册
        this.$socket.registerCallBack('stockData',this.getData)
    },
    mounted(){
        this.initChart()
        // this.getData()
        window.addEventListener('resize',this.screenAdapter)
        //页面加载完成主动进行屏幕的适配
        this.screenAdapter()
        //使用websocket发送给服务器
        this.$socket.send({
            action:'getData',
            socketType:'stockData',
            chartName:'stock',
            value:''
        })
    },
    destroyed() {
        // 在组件销毁时，将监听器取消（防止内存泄漏）
        window.removeEventListener('resize',this.screenAdapter)
        clearInterval(this.timerId)
        //在组件销毁的时候进行webSocket回调函数的取消
        this.$socket.unRegisterCallBack('stockData')
    },
    computed:{
        ...mapState(['theme'])
    },
    watch:{
        theme(){
            this.chartInstance.dispose()  //销毁图表
            this.initChart()  //以最新的主题初始化图表
            this.screenAdapter()  //重新适配屏幕
            this.updatChart()  //更新数据
        }
    },
    methods:{
        //初始化echarts实例对象
        initChart(){
            this.chartInstance = this.$echarts.init(this.$refs.stock_ref,this.theme)
            //对图表初始化配置
            const initOption = {
                title:{
                    text:'▎ 销量和库存分析',
                    top:20,
                    left:20,
                }
            }
            this.chartInstance.setOption(initOption)
            this.chartInstance.on('mouseover',()=>{
                clearInterval(this.timerId) //鼠标移入图表时关闭定时器
            })
            this.chartInstance.on('mouseout',()=>{
                this.startInterval() //鼠标移出图表时重新开启定时器
            })
        },
        // 获取服务器数据
        getData(ret){
            // let {data:ret} = await this.$http.get('stock')
            this.allData = ret
            this.updatChart()
            this.startInterval()
        },
        // 更新图表
        updatChart(){
            //5个圆环图的中心点坐标
            const centerArr = [
                ['18%','40%'],
                ['50%','40%'],
                ['82%','40%'],
                ['34%','75%'],
                ['66%','75%']
            ]
            // 5个圆环图的渐变颜色
            const colorArr = [
                ['#4FF778', '#0BA82C'],
                ['#E5DD45', '#E8B11C'],
                ['#E8821C', '#E55445'],
                ['#5052EE', '#AB6EE5'],
                ['#23E5E5', '#2E72BF']
            ]
            //处理图表数据
            const start = this.currentIndex * 5
            const end = (this.currentIndex + 1) * 5
            const showData = this.allData.slice(start,end)
            const seriesArr = showData.map((item,index)=>{
                return{
                    type:'pie',
                    center:centerArr[index],
                    hoverAnimation:false, //关闭鼠标移入动画
                    labelLine:{
                        show:false   //隐藏指示线
                    },
                    label:{
                        position:'center',
                        color:colorArr[index][0]
                    },
                    data:[
                        {
                            name: item.name + '\n\n' + item.sales,
                            value: item.sales,
                            itemStyle:{
                                color:new this.$echarts.graphic.LinearGradient(0,0,0,1,[
                                    {
                                        offset:0,
                                        color: colorArr[index][0]
                                    },
                                    {
                                        offset:1,
                                        color: colorArr[index][1]
                                    }
                                ])
                            }
                        },
                        {
                            value: item.stock,
                            itemStyle:{
                                color:'#333843'
                            }
                        }
                    ]
                }
            })
            const updataOption = {
                series:seriesArr
            }
            this.chartInstance.setOption(updataOption)
        },
        //当浏览器窗口发生变化时，改变图表的大小
        screenAdapter(){
            //图表标题的大小
            this.titleFontSize = this.$refs.stock_ref.offsetWidth / 100 * 3.6
            const innerRadius = this.titleFontSize * 2.8 //内圆半径
            const outterRadius = innerRadius * 1.125  //外圆半径
            //和分辨率大小相关的配置项
            const adapterOption = {
                title:{
                    textStyle:{
                        fontSize:this.titleFontSize
                    }
                },
                series:[
                    {
                        type:'pie',
                        radius: [outterRadius,innerRadius],
                        label:{
                            fontSize: this.titleFontSize / 1.5
                        }
                    },
                    {
                        type:'pie',
                        radius: [outterRadius,innerRadius],
                        label:{
                            fontSize: this.titleFontSize / 1.5
                        }
                    },
                    {
                        type:'pie',
                        radius: [outterRadius,innerRadius],
                        label:{
                            fontSize: this.titleFontSize / 1.5
                        }
                    },
                    {
                        type:'pie',
                        radius: [outterRadius,innerRadius],
                        label:{
                            fontSize: this.titleFontSize / 1.5
                        }
                    },
                    {
                        type:'pie',
                        radius: [outterRadius,innerRadius],
                        label:{
                            fontSize: this.titleFontSize / 1.5
                        }
                    },
                ]
            }
            this.chartInstance.setOption(adapterOption)
            // 调用图表的resize方法
            this.chartInstance.resize()
        },
        startInterval(){
            if(this.timerId){
                clearInterval(this.timerId)
            }
            this.timerId = setInterval(()=>{
                this.currentIndex++
                if(this.currentIndex > 1){
                    this.currentIndex = 0
                }
                this.updatChart()
            },5000)
        }
    }
}
</script>

<style lang='less' scoped>
</style>